"""
爬虫任务记录模型 - 对应 scraper_task_record 表
"""
from datetime import datetime
from typing import Optional, Dict, Any, List
from sqlalchemy import String, Integer, DECIMAL, DateTime, Text, JSON, TIMESTAMP
from sqlalchemy.orm import Mapped, mapped_column

from axiom_boot.database.base_model import BaseModel


class ScraperTaskRecord(BaseModel):
    """爬虫任务记录模型"""
    
    __tablename__ = "scraper_task_record"
    
    # 主键重新定义
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, comment="主键ID")
    
    # 任务标识
    task_id: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, comment="任务唯一标识ID")
    task_name: Mapped[str] = mapped_column(String(100), nullable=False, comment="任务名称")
    task_type: Mapped[str] = mapped_column(String(50), nullable=False, comment="任务类型(batch_scraping/single_scraping等)")
    
    # 任务配置
    target_site: Mapped[Optional[str]] = mapped_column(String(100), comment="目标网站域名")
    target_count: Mapped[int] = mapped_column(Integer, default=0, comment="目标处理数量")
    concurrent_limit: Mapped[int] = mapped_column(Integer, default=1, comment="并发限制数")
    
    # 任务状态
    task_status: Mapped[str] = mapped_column(String(20), default="pending", comment="任务状态(pending/running/completed/failed/cancelled)")
    start_time: Mapped[Optional[datetime]] = mapped_column(DateTime, comment="任务开始时间")
    end_time: Mapped[Optional[datetime]] = mapped_column(DateTime, comment="任务结束时间")
    duration_seconds: Mapped[Optional[int]] = mapped_column(Integer, comment="任务执行时长(秒)")
    
    # 执行结果统计
    total_processed: Mapped[int] = mapped_column(Integer, default=0, comment="总处理数量")
    success_count: Mapped[int] = mapped_column(Integer, default=0, comment="成功数量")
    failed_count: Mapped[int] = mapped_column(Integer, default=0, comment="失败数量")
    success_rate: Mapped[Optional[float]] = mapped_column(DECIMAL(5, 2), comment="成功率(%)")
    
    # 性能指标
    avg_processing_time: Mapped[Optional[float]] = mapped_column(DECIMAL(8, 2), comment="平均处理时间(秒/条)")
    throughput: Mapped[Optional[float]] = mapped_column(DECIMAL(8, 2), comment="处理速度(条/分钟)")
    
    # 错误信息
    error_summary: Mapped[Optional[str]] = mapped_column(Text, comment="错误汇总信息")
    failed_items: Mapped[Optional[List[Dict[str, Any]]]] = mapped_column(JSON, comment="失败项目详情")
    
    # 配置和环境
    config_params: Mapped[Optional[Dict[str, Any]]] = mapped_column(JSON, comment="任务配置参数")
    execution_environment: Mapped[Optional[str]] = mapped_column(String(100), comment="执行环境信息")

    def __repr__(self):
        return f"<ScraperTaskRecord(task_id='{self.task_id}', task_name='{self.task_name}', status='{self.task_status}')>"
